<?php
namespace CookieAuth;

use HttpRequester\CurlFacade;

abstract class BaseLogin
{
    public static $requester;
    protected $request_url;
    protected $cookie_enable = true;
    protected $cookie_file = __CLASS__.'_cookie.txt';
    protected $cache_key;
    protected $cache_ttl = 86400000;

    /**
     * __construct
     *
     * @param string $url
     */
    public function __construct($url = null, CurlFacade $requester = null)
    {
        $url and $this->request_url = $url;
        $requester === null and static::$requester = CurlFacade::getInstance() or static::$requester = $requester;
    }

    /**
     * request via get
     *
     * @param  array $configs
     * @return mixed
     */
    public function get($url = '', array $configs = [])
    {
        $url === '' and $url = $this->request_url;
        $options = $this->getCurlConfig($configs);
        return static::$requester->get($url, $options);
    }

    /**
     * request via post
     *
     * @param  array $configs
     * @return mixed
     */
    public function post($url = '', $data = '' ,array $configs = [])
    {
        $url === '' and $url = $this->request_url;
        $options = $this->getCurlConfig($configs);
        return static::$requester->post($url, $data ,$options);
    }

    public function getCurlInfo()
    {
        return static::$requester->getLastRequestInfo();
    }

    /**
     * getCurlConfig
     *
     * @param  array $config
     * @return array
     */
    public function getCurlConfig(array $config = [])
    {
        $data = [
            CURLOPT_ENCODING => 'gzip, deflate, sdch',
        ];
        if($this->cookie_enable === true){
            $data[CURLOPT_COOKIEJAR] = $this->cookie_file;
            $data[CURLOPT_COOKIEFILE] = $this->cookie_file;
        }
        return array_replace($data, $config);
    }

    /**
     * get http request header
     *
     * @param  array  $header
     * @return array
     */
    abstract public function getHeaders(array $header = []);


    /**
     * getCacheKey
     *
     * @param string $string
     * @return string
     */
    public function getCacheKey($string)
    {
        return 'ShopLogin:'.__CLASS__.':'.(is_string($string) ? $string : md5(serialize($string)));
    }

    /**
     * buildUrl
     *
     * @param  string $url
     * @param  array  $params
     * @return string
     */
    protected function buildUrl($url = '', array $params = [])
    {
        return $url.(stripos($url, '?') === false ? '?' : '&').http_build_query($params);
    }
}
